package cn.gz.demo.ui;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.databinding.DataBindingUtil;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.gz.demo.R;
import cn.gz.demo.databinding.BannerMeBinding;
import cn.gz.demo.ui.base.BaseActivity;
import cn.gz.demo.view.CustomTransformer;

//importandroidx.viewpager.widget.PagerAdapter;

/**
 * Created by Liuyz on 2017/6/5.
 */
public class BannerMeActivity extends BaseActivity {
    private BannerMeBinding binding;
    private ArrayList<ImageView> images;
    private ImageAdapter imageadapter;

    // 定时任务
    private ScheduledExecutorService scheduledExecutorService;
    private boolean isRunning;
    private int index = 0;
    private ViewPager.OnPageChangeListener mOnPageChangeListener;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (imageadapter.getCount() <= 0) {
                return;
            }
            gotoForward();
        }
    };

    private TranslateAnimation mShowAction, mHiddenAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_banner_me);
        initView();

        binding.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.layout.getVisibility() == View.VISIBLE) {
                    AnimR();
                } else {
                    AnimL();
                }
            }
        });
    }

    TranslateAnimation taR;
    AlphaAnimation alO;
    AnimationSet setR;

    public void AnimR() {
        if (null == taR) {
            taR = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            taR.setDuration(500);
            taR.setFillAfter(true);
            alO = new AlphaAnimation(1, 0.2f); //0表示完全透明。1表示不透明
            alO.setDuration(500);
            alO.setFillAfter(true);
            setR = new AnimationSet(false);
            setR.addAnimation(taR);
            setR.addAnimation(alO);
            setR.setFillAfter(true);
        }
        binding.layout.startAnimation(setR); //iv表示动画显示显示在哪个地方 通过findviewbyid拿到
        setR.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                binding.layout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    TranslateAnimation taL;
    AlphaAnimation alT;
    AnimationSet setL;

    public void AnimL() {
        if (null == taL) {
            taL = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            taL.setDuration(500);
            taL.setFillAfter(true);
            alT = new AlphaAnimation(0.2f, 1); //0表示完全透明。1表示不透明
            alT.setDuration(500);
            alT.setFillAfter(true);
            setL = new AnimationSet(false);
            setL.addAnimation(taL);
            setL.addAnimation(alT);
            setL.setFillAfter(true);
        }
        binding.layout.startAnimation(setL); //iv表示动画显示显示在哪个地方 通过findviewbyid拿到
        setL.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                binding.layout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void initView() {
        // 图片
        int[] imageResID = new int[]{R.mipmap.welcome_pic1, R.mipmap.welcome_pic2, R.mipmap.welcome_pic3,
                R.mipmap.welcome_pic1, R.mipmap.welcome_pic2, R.mipmap.welcome_pic3};

        images = new ArrayList<ImageView>();
        for (int i = 0; i < imageResID.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(imageResID[i]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            images.add(imageView);
        }

        RadioGroup.LayoutParams layout = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
        layout.setMargins(8, 0, 8, 0);  //设置间距
        for (int i = 0; i < imageResID.length; i++) {
            RadioButton rb = new RadioButton(this);
            rb.setId(i + 1);
            rb.setBackgroundResource(R.drawable.circle_selector);
            rb.setButtonDrawable(getResources().getDrawable(R.color.transparent));
            rb.setLayoutParams(layout);
            rb.setWidth(32);
            rb.setHeight(32);
            binding.bannerCircle.addView(rb);
        }

        ((RadioButton) binding.bannerCircle.getChildAt(0)).setChecked(true);
        imageadapter = new ImageAdapter();
        binding.bannerViewpager.setAdapter(imageadapter);
        binding.bannerViewpager.setPageTransformer(true, new CustomTransformer());
        binding.bannerViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Log.e("abc", "..........." + position);
                index = position;
                ((RadioButton) binding.bannerCircle.getChildAt(position % images.size())).setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
//        startBanner();
    }

    private class ImageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
//            return images.size();
            return Integer.MAX_VALUE;
        }

        // 指定本次页面( arg1 )将要显示的内容与当前页面( arg0 )的内容是否一致
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
//            return arg0.equals(arg1);
            return arg0 == arg1;
        }

        // 添加页面
        @Override
        public Object instantiateItem(ViewGroup viewpager, int position) {

//            ((ViewPager) viewpager).addView(images.get(position));
//            return images.get(position);
            ImageView imageView = (ImageView) images.get(position % images.size());
            if (imageView.getParent() != null) {
                ((ViewPager) imageView.getParent()).removeView(imageView);
            }
            viewpager.addView(images.get(position % images.size()));
            return images.get(position % images.size());
        }

        // 销毁页面
        @Override
        public void destroyItem(ViewGroup viewpager, int position, Object object) {
//            ((ViewPager) viewpager).removeView(images.get(position));
//            ((ViewPager) viewpager).removeView((View) object);
//            ((ViewPager) viewpager).removeView(images.get(position % images.size()));
        }
    }


    /**
     * 向后一页
     */
    public void gotoForward() {
        if (null != binding.bannerViewpager) {
            binding.bannerViewpager.setCurrentItem((index + 1) % images.size());//向后一页
        }
    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {
        @Override
        public void run() {
            synchronized (BannerMeActivity.class) {
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    public void startBanner() {
        if (!isRunning) {
            isRunning = true;
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 5,
                    TimeUnit.SECONDS);
        }
    }

    public void stopBanner() {
        if (isRunning) {
            isRunning = false;
            scheduledExecutorService.shutdown();
        }
    }

}
